package middleware.p2p.transaction.log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.GregorianCalendar;

import javax.ejb.Stateless;

import middleware.p2p.transaction.TransactionResponse;

/**
 * Session Bean implementation class TransactionLogger
 */
@Stateless(name="TransactionLogger")
public class TransactionLogger implements TransactionLoggerLocal {
    /**
     * Default constructor. 
     */
    public TransactionLogger() {
    	super();
    }
    private boolean writeOnFile(String trans,String logLine,boolean coordinator) {
    	String roleFolder=(coordinator?"coordinator":"partecipant");
    	File logFile=new File(".."+File.separator+"logs"+File.separator+"transaction"+File.separator+roleFolder+File.separator+trans+".log");
    	logFile.getParentFile().mkdirs();
    	try {
			FileOutputStream fos=new FileOutputStream(logFile, true);
			PrintStream outFile=new PrintStream(fos);
			outFile.println(logLine);
			outFile.close();
			fos.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}    	
    }
	@Override
	public boolean writeComplete(String transId) {
		boolean res=writeOnFile(transId,"COMPLETE",true);
		File logFile=new File(".."+File.separator+"logs"+File.separator+"transaction"+File.separator+"coordinator"+File.separator+transId+".log");
		logFile.renameTo(new File(logFile.getAbsolutePath()+"_completed_"+GregorianCalendar.getInstance().getTimeInMillis()));
		return res; 
	}
	@Override
	public boolean writeDone(String transId) {
		boolean res=writeOnFile(transId,"DONE",false);
		File logFile=new File(".."+File.separator+"logs"+File.separator+"transaction"+File.separator+"partecipant"+File.separator+transId+".log");
		logFile.renameTo(new File(logFile.getAbsolutePath()+"_completed_"+GregorianCalendar.getInstance().getTimeInMillis()));
		return res; 
	}
	@Override
	public boolean writeCoordinatorDecision(String trans, boolean decision) {
		String logDecision=(decision?"GLOBAL_COMMIT":"GLOBAL_ABORT");
		return writeOnFile(trans,logDecision,true);
	}

	@Override
	public boolean writePartecipantVote(String trans, boolean vote) {
		String logVote=(vote?"READY":"NOT_READY");
		return writeOnFile(trans,logVote,false);
	}

	@Override
	public boolean writePrepare(String trans) {
		return writeOnFile(trans,"PREPARE",true);
	}
	@Override
	public boolean writeResponse(String trans, TransactionResponse resp) {
		String logResponse=((resp==TransactionResponse.Commit)?"COMMIT":"ABORT");
		return writeOnFile(trans,logResponse,false);
	}
	@Override
	public boolean writeLink(String trans, String wsdl) {
		return writeOnFile(trans,"LINK "+wsdl,true);
	}
}
